#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/opencv.hpp"

#include "utils.hpp"

uint64_t time_usec(void) 
{

    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec*1000000ULL + ts.tv_nsec/1000;
}

int load_image(const char *filename, void *img_data, size_t size)
{
    FILE *f = fopen(filename, "rb");
    if (f == NULL) {
        return -1;
    };
    fread(img_data, size, 1, f);
    fclose(f);
    return 0;
};

int load_image(const char *filename, void *img_data, int &h, int &w, int &stride)
{
    cv::Mat img = cv::imread(filename);
    cv::Mat gray;
    cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
    h = gray.rows;
    w = gray.cols;
    stride = w;
    uint8_t *data = (uint8_t *)img_data;
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            data[i*w+j] = gray.at<uint8_t>(i, j);
        }
    }
    return 0;
}

void save_image(const char *filename, void *img_data, int h, int w, int stride)
{
    cv::Mat img(h, w, CV_8UC1, img_data);
    cv::imwrite(filename, img);
    // cv::Mat img(height*4, width, CV_8UC1, frame_data->img_head);
    // _top_left_img = img(cv::Rect(cv::Point(0, 0), cv::Point(width, height))).clone();
    // _top_right_img = img(cv::Rect(cv::Point(0, height), cv::Point(width, height*2))).clone();
    // _bottom_left_img = img(cv::Rect(cv::Point(0, height*2), cv::Point(width, height*3))).clone();
    // _bottom_right_img = img(cv::Rect(cv::Point(0, height*3), cv::Point(width, height*4))).clone();
}
